#! python3
# backupToZip.py
# Copies an entire folder and its contents into
# a zip file whose filename increments.

import zipfile, os, shutil


def backupToZip(folder):
    # Backup the entire contents of "folder" into a zip file.

    folder = os.path.abspath(folder)  # make sure folder is absolute

    # Figure out the filename this code should used based on
    # what files already exist.
    number = 1
    while True:
        zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
        if not os.path.exists(zipFilename):
            break
        number = number + 1

    # Create the zip file.
    print('Creating %s...' % (zipFilename))
    backupZip = zipfile.ZipFile(zipFilename, 'w')

    # Walk the entire folder tree and compress the files in each folder.
    for foldername, subfolders, filenames in os.walk(folder):
        print('Adding files in %s...' % (foldername))
        # Add the current folder to the ZIP file.
        backupZip.write(foldername)

        # Add all the files in this folder to the ZIP file.
        for filename in filenames:
            if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):
                continue  # don't backup the backup ZIP files
            backupZip.write(os.path.join(foldername, filename))
    backupZip.close()
    print('Done.')


def copy_folder_to_zip(source_folder, zip_base_name):
    """
    Copies an entire folder and its contents into a zip file with an incrementing filename.

    Parameters:
    - source_folder (str): The path to the source folder.
    - zip_base_name (str): The base name for the zip file (without the extension).
    """
    zip_counter = 1
    zip_filename = f"{zip_base_name}_{zip_counter}.zip"

    while os.path.exists(zip_filename):
        zip_counter += 1
        zip_filename = f"{zip_base_name}_{zip_counter}.zip"

    shutil.make_archive(zip_base_name, 'zip', source_folder)
    os.rename(f"{zip_base_name}.zip", zip_filename)

    print(f"Folder '{source_folder}' copied to '{zip_filename}'.")


# Example usage
source_folder = 'F:\\github\\test'  # Replace with your source folder path
zip_base_name = 'test'  # Replace with your desired base name for the zip file

copy_folder_to_zip(source_folder, zip_base_name)

# backupToZip('F:\\github\\test')
